package com.atguigu.lease.web.app.service.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.print.attribute.standard.JobKOctets;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private Client client;
    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) throws Exception {
        Object code = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + phone);
        if (!ObjectUtils.isEmpty(code)){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //设置一个随机生成的六位验证码
        int randomNum = (int)(Math.random() * 900000) + 100000;
        //将验证码保存到redis中
        redisTemplate.opsForValue().set(RedisConstant.APP_LOGIN_PREFIX+phone,randomNum,
                RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC, TimeUnit.SECONDS);
        //定义发送短信格式
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setSignName("阿里云短信测试");
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\""+randomNum+"\"}\n");
        //发送短信
        client.sendSms(sendSmsRequest);
    }

    @Override
    public String login(LoginVo loginVo) {
        //获取验证码
        Object code = redisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone());
        //判断验证码是否为空
        if(ObjectUtils.isEmpty(code)){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //判断验证码是否正确
        if (!code.toString().equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //查询手机号是否存在,不存在就是注册
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoLambdaQueryWrapper);
        if (userInfo == null){
            //手机号没有注册过
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setAvatarUrl("http://www.baidu.com/img/bd_logo.png");
            userInfo.setNickname("佚名"+loginVo.getPhone().substring(loginVo.getPhone().length()-5,loginVo.getPhone().length()));
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfoService.save(userInfo);
        }
        //3.检查用户是否可用（是否被禁用）
        if (userInfo.getStatus() == BaseStatus.DISABLE){
            throw  new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //4.创建token，并返回即可
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());
        return token;
    }
}
